#include "InetAddress.h"

#include <strings.h>
#include <string>

InetAddress::InetAddress(uint16_t port, std::string ip)
{
    bzero(&addr_, sizeof(addr_));
    addr_.sin_family = AF_INET;
    addr_.sin_port = htons(port);
    addr_.sin_addr.s_addr = inet_addr(ip.c_str());
}

InetAddress::InetAddress(sockaddr_in addr)
{
    addr_ = addr;
}

// 注意addr_中的ip、port已经是网络字节序了，输出时要先转换
std::string InetAddress::toIp() const
{
    return inet_ntoa(addr_.sin_addr);
}

std::string InetAddress::toIpPort() const
{
    uint16_t port = ntohs(addr_.sin_port);

    std::string ipport = inet_ntoa(addr_.sin_addr);
    ipport += ":";
    ipport += std::to_string(port);
    return ipport;
}

uint16_t InetAddress::toport() const
{
    return ntohs(addr_.sin_port);
}
